package net.esj.basic.service.impl;

import java.util.ArrayList;
import java.util.List;

import net.esj.basic.plugins.view.easyui.utils.EasyUITreeEntity;
import net.esj.basic.service.TreeService;

@Deprecated
public abstract class TreeServiceImpl<T> extends DefaultServiceImpl implements
		TreeService {
	
	public static String BASE_DEFAULT_PARENT  ="00000000000000000000000000000000";
	
	public static final EasyUITreeEntity TREE_ROOT = new EasyUITreeEntity(BASE_DEFAULT_PARENT,"ROOT");

	@Override
	public List<EasyUITreeEntity> getTree(boolean needRoot){
		List<T> list = getAll();
		List<T> templist = new ArrayList<T>(list);
		List<EasyUITreeEntity> reval = new ArrayList<EasyUITreeEntity>();
		
		if(needRoot){
			EasyUITreeEntity root = createRoot();
			reval.add(root);
			appendChild(templist, root);
		}else{
			for(T t : list){
				if(isRoot(t)){
					EasyUITreeEntity e = createTreeEntity(t);
					reval.add(e);
					templist.remove(t);
				}
			}
			for(EasyUITreeEntity tree:reval){
				appendChild(templist, tree);
			}
		}
		
		return reval;
	}
	
	protected void  appendChild(List<T> list,EasyUITreeEntity tree){
		List<T> reval = new ArrayList<T>(list);
		for(T t : reval){
			if(isChild(tree, t)){
				tree.getChildren().add(createTreeEntity(t));
				list.remove(t);
			}
		}
		if(tree.getChildren().size()>0){
			for(EasyUITreeEntity child: tree.getChildren()){
				appendChild(list, child);
			}
		}
	}
	
	protected abstract EasyUITreeEntity createTreeEntity(T t);
	
	protected abstract boolean isChild(EasyUITreeEntity parent,T t);
	
	protected abstract boolean isRoot(T t);
	
	protected abstract List<T> getAll();
	
	protected abstract EasyUITreeEntity createRoot();
	
	protected abstract boolean hasChild(T t);
}
